﻿
using UnityEngine.EventSystems;

namespace UnityEngine.UI
{
    public class UIButton : Button
    {
        [System.NonSerialized]
        public float CDTimer = 0.5f;
        public System.Action<bool> onHover;
        public System.Action<bool> onPress;

        private string _btnSound = "";
        private float _lastClickTime = 0;
        private ISelectionStateListener[] _selectionStateListeners;

        protected override void Awake()
        {
            base.Awake();
            _selectionStateListeners = GetComponentsInChildren<ISelectionStateListener>();
            _btnSound = Const.Sound.BtnClick;
        }

        public override void OnPointerClick(PointerEventData eventData)
        {
            if (Time.unscaledTime - _lastClickTime < CDTimer)
            {
                return;
            }
            _lastClickTime = Time.unscaledTime;
            PlaySound();
            base.OnPointerClick(eventData);
        }

        private void PlaySound()
        {
            if (string.IsNullOrEmpty(_btnSound))
                return;
            SoundManager.Instance.PlayOneShot(_btnSound);
        }

        public override void OnPointerEnter(PointerEventData eventData)
        {
            base.OnPointerEnter(eventData);
            onHover?.Invoke(true);
        }
        public override void OnPointerExit(PointerEventData eventData)
        {
            base.OnPointerExit(eventData);
            onHover?.Invoke(false);
        }
        public override void OnPointerDown(PointerEventData eventData)
        {
            base.OnPointerDown(eventData);
            onPress?.Invoke(true);
        }
        public override void OnPointerUp(PointerEventData eventData)
        {
            base.OnPointerUp(eventData);
            onPress?.Invoke(false);
        }

        protected override void InstantClearState()
        {
            base.InstantClearState();
            if (_selectionStateListeners != null)
            {
                for (int i = 0; i < _selectionStateListeners.Length; i++)
                {
                    _selectionStateListeners[i].InstantClearState();
                }
            }
        }

        protected override void DoStateTransition(SelectionState state, bool instant)
        {
            base.DoStateTransition(state, instant);
            if (_selectionStateListeners != null)
            {
                for (int i = 0; i < _selectionStateListeners.Length; i++)
                {
                    _selectionStateListeners[i].DoStateTransition((int)state);
                }
            }
        }
    }
}
